#define DEBUG 0
#include "rtmp.h"
#include "boost/asio/write.hpp"
#include <cstdio>
#include <vector>
#include <log.h>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;

void* rtmp::s_flv = NULL;
//void writeToken(boost::system::error_code& error, size_t transferred)
//{
	//if (!error) {
		//ALOGD("rtmp server send %lld to client", transferred);
	//}
//}

int send(void* param, const void* header, size_t len, const void* payload, size_t bytes)
{
	tcp::socket* s = (tcp::socket*)param;
	std::vector<char> buf2;
	buf2.insert(buf2.end(), (const char*)header, (const char*)header+len);
	buf2.insert(buf2.end(), (const char*)payload, (const char*)payload+bytes);
	return boost::asio::write(*s, boost::asio::buffer(buf2));
}

int onpublish(void* param, const char* app, const char* stream, const char* type)
{
	printf("rtmp_server_onpublish(%s, %s, %s)\n", app, stream, type);
	return 0;
}

int onscript(void* param, const void* script, size_t bytes, uint32_t timestamp)
{
	return flv_writer_input(rtmp::s_flv, FLV_TYPE_SCRIPT, script, bytes, timestamp);
}

int onvideo(void* param, const void* data, size_t bytes, uint32_t timestamp)
{
	return flv_writer_input(rtmp::s_flv, FLV_TYPE_VIDEO, data, bytes, timestamp);
}

int onaudio(void* param, const void* data, size_t bytes, uint32_t timestamp)
{
	return flv_writer_input(rtmp::s_flv, FLV_TYPE_AUDIO, data, bytes, timestamp);
}

rtmp::rtmp(void* socket)
{
	s_flv = flv_writer_create("flv.flv");
	rtmp_server_handler_t handler;
	mHandler = &handler;
	mHandler->send = send;
	mHandler->onpublish = onpublish;
	mHandler->onscript = onscript;
	mHandler->onvideo = onvideo;
	mHandler->onaudio = onaudio;
	mServer = rtmp_server_create(socket, mHandler);
}

void rtmp::rtmp_recv(const char* buf, size_t transferred)
{
	int state = rtmp_server_getstate(mServer);
	ALOGD("rtmp_server_getstate: %d", state);
	int r = rtmp_server_input(mServer, (const uint8_t*)buf, transferred);
	ALOGD("rtmp_server_input: %d", r);
}

rtmp::~rtmp()
{
	flv_writer_destroy(s_flv);
	rtmp_server_destroy(mServer);
}
